import { useEffect, useRef, useState } from 'react';
import { List } from 'lucide-react';
import './Select.css';

/**
 * Select 下拉选择对话框组件
 * @param {string} title - 标题
 * @param {string} message - 提示消息
 * @param {Array} options - 选项数组 [{ value, label }]
 * @param {string} defaultValue - 默认值
 * @param {string} confirmText - 确认按钮文字
 * @param {string} cancelText - 取消按钮文字
 * @param {function} onConfirm - 确认回调，参数为选中的value
 * @param {function} onCancel - 取消回调
 */
export const Select = ({
  title = '选择',
  message,
  options = [],
  defaultValue = '',
  confirmText = '确认',
  cancelText = '取消',
  onConfirm,
  onCancel
}) => {
  const modalRef = useRef(null);
  const [value, setValue] = useState(defaultValue || options[0]?.value || '');

  useEffect(() => {
    const handleEscape = (e) => {
      if (e.key === 'Escape') {
        onCancel?.();
      } else if (e.key === 'Enter') {
        e.preventDefault();
        onConfirm?.(value);
      }
    };

    const handleClickOutside = (e) => {
      if (modalRef.current && !modalRef.current.contains(e.target)) {
        onCancel?.();
      }
    };

    document.addEventListener('keydown', handleEscape);
    document.addEventListener('mousedown', handleClickOutside);

    return () => {
      document.removeEventListener('keydown', handleEscape);
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [value, onCancel, onConfirm]);

  return (
    <div className="select-overlay">
      <div ref={modalRef} className="select-modal">
        <div className="select-icon">
          <List size={32} strokeWidth={2} />
        </div>
        <div className="select-content">
          <h3 className="select-title">{title}</h3>
          {message && <p className="select-message">{message}</p>}
          <select
            className="select-input"
            value={value}
            onChange={(e) => setValue(e.target.value)}
            autoFocus
          >
            {options.map(option => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        </div>
        <div className="select-actions">
          <button 
            className="select-btn select-btn-cancel"
            onClick={onCancel}
          >
            {cancelText}
          </button>
          <button 
            className="select-btn select-btn-confirm"
            onClick={() => onConfirm?.(value)}
          >
            {confirmText}
          </button>
        </div>
      </div>
    </div>
  );
};

